import 'package:get/get.dart';
import '../models/alert_log_model.dart';
import '../repositories/data_repository.dart';
import 'package:flutter/foundation.dart';

/// 告警日志数据服务
/// 
/// 负责告警日志数据的缓存、获取和管理
class AlertLogService extends GetxService {
  // 告警日志数据缓存
  final RxList<AlertLog> cachedAlertLogs = <AlertLog>[].obs;
  
  // 告警状态统计数据
  final RxInt alertLogsTotal = 0.obs;
  final RxInt unconfirmedAlertCount = 0.obs;
  final RxInt alertGeneratedCount = 0.obs;  // 状态0: 产生
  final RxInt alertRecoveredCount = 0.obs;  // 状态1: 恢复
  final RxInt alertConfirmedCount = 0.obs;  // 状态2: 已确认
  
  // 数据是否已加载的标志
  final RxBool isDataLoaded = false.obs;
  
  // 最后加载时间
  Rx<DateTime?> lastLoadTime = Rx<DateTime?>(null);

  // 缓存有效期 (分钟)
  final int cacheValidityMinutes = 5; // 告警日志缓存时间较短，以便及时更新

  // Repository实例
  late final DataRepository _dataRepository;

  @override
  void onInit() {
    super.onInit();
    _dataRepository = Get.find<DataRepository>();
    debugPrint('AlertLogService 已初始化');
  }

  /// 获取所有告警日志数据
  /// 如果有缓存且在有效期内，直接返回缓存
  /// 否则从服务器加载数据并更新缓存
  Future<List<AlertLog>> getAllAlertLogs({bool forceRefresh = false}) async {
    // 检查缓存是否有效
    if (!forceRefresh && isDataLoaded.value && _isCacheValid()) {
      debugPrint('AlertLogService: 使用缓存数据，共${cachedAlertLogs.length}条记录');
      return cachedAlertLogs;
    }

    try {
      debugPrint('AlertLogService: 从服务器加载告警日志数据');
      final response = await _dataRepository.getAllAlertLogs();
      
      // 更新缓存
      alertLogsTotal.value = response.total;
      
      // 如果没有告警日志，直接返回空列表
      if (response.rows.isEmpty) {
        cachedAlertLogs.clear();
        _resetAlertCounts();
        isDataLoaded.value = true;
        lastLoadTime.value = DateTime.now();
        return [];
      }
      
      // 限制最大处理数据量，避免内存问题
      const int maxProcessItems = 100;
      final safeRows = response.rows.length > maxProcessItems 
          ? response.rows.sublist(0, maxProcessItems) 
          : response.rows;
      
      // 更新缓存
      cachedAlertLogs.value = safeRows;
      isDataLoaded.value = true;
      lastLoadTime.value = DateTime.now();
      
      // 计算各状态告警数量
      _calculateAlertStatusCounts();
      
      return safeRows;
    } catch (e) {
      debugPrint('AlertLogService: 加载告警日志数据失败: $e');
      // 如果有缓存数据，返回缓存数据
      if (cachedAlertLogs.isNotEmpty) {
        return cachedAlertLogs;
      }
      // 返回空列表
      return [];
    }
  }
  
  /// 重置告警计数
  void _resetAlertCounts() {
    unconfirmedAlertCount.value = 0;
    alertGeneratedCount.value = 0;
    alertRecoveredCount.value = 0;
    alertConfirmedCount.value = 0;
  }
  
  /// 根据告警日志缓存数据计算各状态告警数量
  void _calculateAlertStatusCounts() {
    int unconfirmedCount = 0;
    int generatedCount = 0;
    int recoveredCount = 0;
    int confirmedCount = 0;
    
    for (final log in cachedAlertLogs) {
      switch (log.status) {
        case 0: // 产生
          generatedCount++;
          unconfirmedCount++;
          break;
        case 1: // 恢复
          recoveredCount++;
          break;
        case 2: // 已确认
          confirmedCount++;
          break;
      }
    }
    
    unconfirmedAlertCount.value = unconfirmedCount;
    alertGeneratedCount.value = generatedCount;
    alertRecoveredCount.value = recoveredCount;
    alertConfirmedCount.value = confirmedCount;
  }

  /// 确认告警
  Future<bool> confirmAlert(int logId) async {
    try {
      final success = await _dataRepository.confirmAlertLog(logId);
      if (success) {
        // 更新缓存中的告警状态
        final index = cachedAlertLogs.indexWhere((log) => log.logId == logId);
        if (index != -1) {
          final updatedLog = cachedAlertLogs[index].copyWith(status: 2);
          cachedAlertLogs[index] = updatedLog;
          
          // 重新计算统计数据
          _calculateAlertStatusCounts();
        }
        
        return true;
      }
      return false;
    } catch (e) {
      debugPrint('AlertLogService: 确认告警失败: $e');
      return false;
    }
  }

  /// 获取主页所需的告警统计数据
  Future<Map<String, dynamic>> getHomeStatistics({bool forceRefresh = false}) async {
    if (forceRefresh || !isDataLoaded.value || !_isCacheValid()) {
      await getAllAlertLogs(forceRefresh: forceRefresh);
    }
    
    // 返回最近5条告警日志和统计数据
    final recentLogs = cachedAlertLogs.length > 5 
        ? cachedAlertLogs.sublist(0, 5) 
        : cachedAlertLogs;
    
    return {
      'logs': recentLogs,
      'total': alertLogsTotal.value,
      'unconfirmedCount': unconfirmedAlertCount.value,
      'generatedCount': alertGeneratedCount.value,
      'recoveredCount': alertRecoveredCount.value,
      'confirmedCount': alertConfirmedCount.value,
    };
  }
  
  /// 根据设备ID获取该设备的告警日志
  Future<List<AlertLog>> getAlertLogsByDeviceId(int deviceId, {bool forceRefresh = false}) async {
    // 确保数据已加载
    if (forceRefresh || !isDataLoaded.value || !_isCacheValid()) {
      await getAllAlertLogs(forceRefresh: forceRefresh);
    }
    
    // 从缓存中筛选该设备的告警日志
    return cachedAlertLogs.where((log) => log.deviceId == deviceId).toList();
  }
  
  /// 根据产品ID获取该产品下的告警日志
  Future<List<AlertLog>> getAlertLogsByProductId(int productId, {bool forceRefresh = false}) async {
    // 确保数据已加载
    if (forceRefresh || !isDataLoaded.value || !_isCacheValid()) {
      await getAllAlertLogs(forceRefresh: forceRefresh);
    }
    
    // 从缓存中筛选该产品的告警日志
    return cachedAlertLogs.where((log) => log.productId == productId).toList();
  }
  
  /// 清除缓存
  void clearCache() {
    cachedAlertLogs.clear();
    isDataLoaded.value = false;
    lastLoadTime.value = null;
    alertLogsTotal.value = 0;
    _resetAlertCounts();
    debugPrint('AlertLogService: 缓存已清除');
  }
  
  /// 检查缓存是否在有效期内
  bool _isCacheValid() {
    if (lastLoadTime.value == null) return false;
    
    final now = DateTime.now();
    final duration = now.difference(lastLoadTime.value!);
    return duration.inMinutes < cacheValidityMinutes;
  }
} 